package suzf.top.kotlinjava.common.security

import org.minbox.framework.api.boot.plugin.security.delegate.ApiBootStoreDelegate
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.stereotype.Component
import suzf.top.kotlinjava.common.exception.ServiceException
import suzf.top.kotlinjava.service.service.UserService

/**
 *  自定义读取用户信息
 *========================
 * Created with IntelliJ IDEA
 * Author:Mr.Su
 * Date:2019/9/28
 * Time:12:15
 * ========================
 */
@Component
class CustomUserStoreDelegate: ApiBootStoreDelegate {

    private val logger = LoggerFactory.getLogger(CustomUserStoreDelegate::class.java)

    @Autowired
    private lateinit var userService: UserService

    /**
     * 返回根据username查询的用户详情对象
     * UserDetails是SpringSecurity提供的用户详情接口
     * 返回的自定义用户对象需实现UserDetails接口
     * @param username 用户名
     * @return
     */
    @Throws(ServiceException::class)
    override fun loadUserByUsername(username: String?): UserDetails? {
        logger.info("CustomUserStoreDelegate{} loadUserByUsername")
        val user = userService.findOneByUserName(username!!) ?: throw  ServiceException("用户：" + username + "不存在")
        return DisableDefaultUserDetails(user)
    }
}
